package jt.classic.app.gdzc;

import jt.classic.app.gdzc.impl.GdzcTemplateImpl;
import jt.classic.app.gdzc.impl.GdzcTemplateItemImpl;

import jt.classic.system.ISystemException;
import jt.classic.system.SimpleManager;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;
import jt.classic.system.utils.AnnexTool;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.limp.basework.Column;
import org.limp.basework.Table;
import org.limp.basework.analyzer.TableRegisterCenter;

import org.limp.mine.DataTrimmerI.DataItemList;
import org.limp.mine.annex.AnnexInfo;

import java.sql.Connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 固定资产模板管理器
 *
 * @author mido
 *
 */
public class GdzcTemplateManager extends SimpleManager {
    /**
     * 构造函数
     * @param conn
     */
    public GdzcTemplateManager(Connection conn) {
        super(conn);
    }

    public GdzcTemplate getTemplateById(String id) throws ISystemException {
        GdzcTemplate template = null;

        String sql = "SELECT * FROM APP_GDZC_TEMPLATE WHERE ID = ?";

        DataItemList dil = this.trimmerI.createDIL();
        dil.set(id);

        Map info = this.trimmerI.searchSingleData(sql, dil);

        if (info != null) {
            template = new GdzcTemplateImpl();

            AnnexTool tool = new AnnexTool(this.conn);

            AnnexInfo[] annexs = tool.getAnnexs(id, "APP_GDZC_TEMPLATE");

            info.put("ALLFREE", annexs);

            String userId = (String) info.get("USERID");

            UserManager umanager = new UserManager(this.conn);

            IUser user = umanager.getUserById("userId");

            info.put("IUSER", user);

            info.put(GdzcTemplateImpl.PROP_COMMON,
                this.getTemplateItems(id, GdzcTemplateImpl.PROP_COMMON));
            info.put(GdzcTemplateImpl.PROP_BASE,
                this.getTemplateItems(id, GdzcTemplateImpl.PROP_BASE));
            info.put(GdzcTemplateImpl.PROP_CONFIG,
                this.getTemplateItems(id, GdzcTemplateImpl.PROP_CONFIG));
            info.put(GdzcTemplateImpl.PROP_FINANCE,
                this.getTemplateItems(id, GdzcTemplateImpl.PROP_FINANCE));
            info.put(GdzcTemplateImpl.PROP_MAINTEN,
                this.getTemplateItems(id, GdzcTemplateImpl.PROP_MAINTEN));

            template.reload(info);
        }

        return template;
    }

    /**
     * 获取模板项列表
     * @param id 模板id
     * @param type 模板属性类别
     * @return List
     * @throws ISystemException
     */
    public List getTemplateItems(String id, String type)
        throws ISystemException {
        String sql = "SELECT * FROM APP_GDZC_TEMPITEM WHERE TEMPID = ? AND PROPKEY = ?";

        DataItemList dil = this.trimmerI.createDIL();
        dil.set(id);
        dil.set(type);

        List list = this.trimmerI.searchMultiData(sql, dil);

        if ((list != null) && !list.isEmpty()) {
            TableRegisterCenter center = TableRegisterCenter.getInstance();

            for (int i = 0; i < list.size(); i++) {
                Map info = (Map) list.get(i);

                String columnName = (String) info.get("COLUMNNAME");
                String tableName = (String) info.get("TABLENNAME");

                Table table = center.findTable(tableName);

                try {
                    Column column = table.column(columnName);
                    info.put("COLUMN", column);
                } catch (Exception ex) {
                    throw new ISystemException("get template item[column:" +
                        columnName + ",table:" + tableName + "] error.", ex);
                }

                GdzcTemplateItem item = new GdzcTemplateItemImpl();

                item.reload(info);

                list.set(i, item);
            }
        }

        return list;
    }

    /**
     * 获取用户可进行登记的资产模板
     * @param user 用户
     * @param type 资产类型
     * @return List
     */
    public List getTemplate4DJ(IUser user, String typeid)
        throws ISystemException {
        String sql = "SELECT ID,USERID FROM APP_GDZC_TEMPLATE WHERE TYPEID = ? AND TSTATUS = 0";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(typeid);

        List resultList = new ArrayList();

        List list = this.trimmerI.searchMultiData(sql, dil);

        if ((list != null) && !list.isEmpty()) {
            PurviewManager manager = new PurviewManager(this.conn);

            for (int i = 0; i < list.size(); i++) {
                Map info = (Map) list.get(i);
                String id = (String) info.get("ID");
                String userId = (String) info.get("USERID");

                if (manager.purview(id, "gztemp", user) == 3) {
                    resultList.add(this.getTemplateById(id));
                }
            }
        }

        return resultList;
    }

    /**
     * 获取模板项json
     * @param tn 模板属性(表名称)
     * @return String
     */
    public static String getItemJson(String tn) {
        TableRegisterCenter center = TableRegisterCenter.getInstance();

        List resultList = new ArrayList();

        if (center.containsTable(tn)) {
            Table table = center.findTable(tn);

            List columnList = table.normalColumns();

            if ((columnList != null) && !columnList.isEmpty()) {
                for (int i = 0; i < columnList.size(); i++) {
                    Map temp = new HashMap();

                    Column column = (Column) columnList.get(i);

                    if (!column.isPremaryKey()) {
                        temp.put("name", column.getName());
                        temp.put("memo", column.getDescription());
                        temp.put("tp", column.getType().toString());

                        resultList.add(temp);
                    }
                }
            }
        }

        JSONArray jsonArray = JSONArray.fromObject(resultList);

        String jsonString = "{\"totalCount\":\"" + resultList.size() +
            "\",\"columnList\":";
        jsonString += jsonArray.toString();
        jsonString += "}";

        return jsonString;
    }

    /**
     * 获取模板json字符串
     * @param template 固定资产模板
     * @param params 辅助参数
     * @return String
     */
    public static String getTemplateJson(GdzcTemplate template, Map params) {
        Map templateJsonMap = new HashMap();

        templateJsonMap.put("id", template.id());
        templateJsonMap.put("name", template.iname());
        templateJsonMap.put("desc", template.idesc());
        templateJsonMap.put("createtime", template.icreatetime());
        templateJsonMap.put("userid", template.iuserid());
        templateJsonMap.put("username", template.iusername());
        templateJsonMap.put("groupid", template.igroupid());
        templateJsonMap.put("groupname", template.igroupname());
        templateJsonMap.put("typeid", template.itypeid());
        templateJsonMap.put("typename", template.itypename());
        templateJsonMap.put("typecode", template.itypecode());

        AnnexInfo[] annexs = template.iprinttemplates();

        List annexList = new ArrayList();

        if ((annexs != null) && (annexs.length > 0)) {
            for (int kk = 0; kk < annexs.length; kk++) {
                AnnexInfo ai = annexs[kk];
                Map annexInfo = new HashMap();
                annexInfo.put("id", ai.getID());
                annexInfo.put("name", ai.getName());
                annexInfo.put("type", ai.getType());
                annexInfo.put("folder", ai.getRepository());
                annexInfo.put("url", ai.getLinkString());
                annexList.add(annexInfo);
            }
        }

        templateJsonMap.put("printannex", annexList);

        List commonList = template.items(GdzcTemplateImpl.PROP_COMMON);
        templateJsonMap.put(GdzcTemplateImpl.PROP_COMMON,
            getItemJsonList(commonList, params));

        List baseList = template.items(GdzcTemplateImpl.PROP_BASE);
        templateJsonMap.put(GdzcTemplateImpl.PROP_BASE,
            getItemJsonList(baseList, params));

        List configList = template.items(GdzcTemplateImpl.PROP_CONFIG);
        templateJsonMap.put(GdzcTemplateImpl.PROP_CONFIG,
            getItemJsonList(configList, params));

        List financeList = template.items(GdzcTemplateImpl.PROP_FINANCE);
        templateJsonMap.put(GdzcTemplateImpl.PROP_FINANCE,
            getItemJsonList(financeList, params));

        List maintenList = template.items(GdzcTemplateImpl.PROP_MAINTEN);
        templateJsonMap.put(GdzcTemplateImpl.PROP_MAINTEN,
            getItemJsonList(maintenList, params));

        JSONObject obj = JSONObject.fromObject(templateJsonMap);

        return obj.toString();
    }

    public static List getItemJsonList(List itemList, Map params) {
        if ((itemList != null) && !itemList.isEmpty()) {
            for (int i = 0; i < itemList.size(); i++) {
                GdzcTemplateItem item = (GdzcTemplateItem) itemList.get(i);

                Map itemJsonMap = new HashMap();

                itemJsonMap.put("id", item.id());
                itemJsonMap.put("name", item.iname());
                itemJsonMap.put("label", item.ilabel());
                itemJsonMap.put("desc", item.idesc());
                itemJsonMap.put("dvalue", item.idvalue());
                itemJsonMap.put("checkblank", item.icheck(0));
                itemJsonMap.put("checktype", item.icheck(1));
                itemJsonMap.put("param", item.iovalue());
                itemJsonMap.put("proptype", item.iproptype());
                itemJsonMap.put("propname", item.iproptypename());
                itemJsonMap.put("type", item.itype());
                itemJsonMap.put("templateid", item.itemplateid());
                itemJsonMap.put("column", item.icolumn().getName());
                itemJsonMap.put("table", item.icolumn().associateTable().getName());
                itemJsonMap.put("formname", item.icolumn().getFormName());
                itemJsonMap.put("columntype",
                    item.icolumn().getType().toString());
                itemJsonMap.put("columndesc", item.icolumn().getDescription());

                itemList.set(i, itemJsonMap);
            }
        }

        return itemList;
    }
}
